<?php
namespace app\store\controller\food\shop;

use app\store\controller\food\Controller;
use app\store\model\Table as TableModel;
use app\store\model\Shop as ShopModel;
use hema\wechat\Driver;
use think\facade\View;

/**
 * 餐桌/包间控制器
 */
class Table extends Controller
{
     /**
     * 列表
     */
    public function index($shop_id = 0, string $search = '')
    {
        if(!$this->is_admin OR $this->shop_mode == 10){
            $shop_id = $this->shop_id;
        }
        $model = new ShopModel;
        $category = $model->getList(false);
        $model = new TableModel;
        $list = $model->getList($shop_id,0,$search);
        return View::fetch('index', compact('list','category','shop_id','search'));
    }

    /**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            $model = new ShopModel;
            $category = $model->getList(false);
            return View::fetch('add', compact('category'));
        }
        $model = new TableModel;
        $data = $this->postData('data');
        if(!$this->is_admin OR $this->shop_mode == 10){
            $data['shop_id'] = $this->shop_id;
        }
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('food.shop.table/index'));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = TableModel::get($id);
        if($model->remove()) {
            return $this->renderSuccess('删除成功');
        }
        $error = $model->getError() ?: '删除失败';
        return $this->renderError($error);
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        // 详情
        $model = TableModel::get($id);
        if (!$this->request->isAjax()) {
            $shop = new ShopModel;
            $category = $shop->getList(false);
            return View::fetch('edit', compact('model', 'category'));
        }
        // 更新记录
        if ($model->edit($this->postData('data'))) {
            return $this->renderSuccess('更新成功', url('food.shop.table/index'));
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }

    /**
     * 二维码
     */
    public function qrcode($id, $shop_id)
    {
        $wx = new Driver;
        $url = $wx->getQrCode($this->applet_id,'table-' . $shop_id . '-' . $id);
        return redirect($url);
    }

}
